package com.grape.rabbitmq.queue.core.simple;

import com.grape.rabbitmq.queue.util.MQConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static com.grape.rabbitmq.queue.core.simple.SimpleConstant.QUEUE_NAME;

/**
 * 描述:简单模式消费者
 * @author: myx
 * @date: 2019-04-30
 * Copyright © 2019-grape. All rights reserved.
 */
public class SimpleCustomer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.获取连接
        Connection newConnection = MQConnectionUtils.newConnection(SimpleConstant.VIRTUALHOST_NAME);
        // 2.获取通道
        Channel channel = newConnection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String msgString = new String(body, "UTF-8");
                System.out.println("消费者获取消息:" + msgString);
            }
        };
        // 3.监听队列 如果为true表示自动应答模式
        channel.basicConsume(QUEUE_NAME, true, defaultConsumer);
    }
}
